package com.innovativethinking.domain.service;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import com.google.appengine.api.users.User;
import com.google.inject.Inject;
import com.innovativethinking.domain.KanbanTweet;

public class KanbanTweetServiceImpl implements KanbanTweetService {

	@Inject private PersistenceManagerFactory pmf = null;
	
	@Override
	public String update(Long kanbanId, String operation) {

		KanbanTweet kt = null;
		
		PersistenceManager persistenceManager = persistenceManager();
		
		try {
			kt = persistenceManager.getObjectById(KanbanTweet.class, kanbanId);
			
			kt.updateBuffer(operation);
			
	    } finally {
	    	persistenceManager.close();
	    }
	    
	    return kt.getBuffer();
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<KanbanTweet> getMyTweetsByBuffer(String buffer, User user) {
		
		PersistenceManager persistenceManager = persistenceManager();
		
		Query query = persistenceManager.newQuery(KanbanTweet.class);
		query.setFilter("owner == userParam && buffer == bufferParam");
		query.setOrdering("registerDate desc");
		query.declareImports("import com.google.appengine.api.users.User;");
		query.declareParameters("User userParam, String bufferParam");
		

	    List<KanbanTweet> allMyTweets = new ArrayList<KanbanTweet>();
		
	    try {
	    	allMyTweets = (List<KanbanTweet>) query.execute(user, buffer);
	    } finally {
	    	query.closeAll();
	    }	
		
		
		return allMyTweets;
	}

	private PersistenceManager persistenceManager() {
		PersistenceManager persistenceManager = pmf.getPersistenceManager();
		return persistenceManager;
	}

	@Override
	public void save(KanbanTweet tweet) {
		
		PersistenceManager persistenceManager = persistenceManager();
		
		if (tweet != null && !"".equals(tweet.getTweet().trim())) {
			
			try {
				persistenceManager.makePersistent(tweet);
			} finally {
				persistenceManager.close();
			}			
		}
	}

}
